package cn.yym.test.dao.impl;


import cn.yym.test.dao.UserDao;
import cn.yym.test.domain.User;
import cn.yym.test.utils.DbUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {

    @Override
    public User checkUser(String username, String password) {
        Connection connection = DbUtils.getConnection();
        User user = null;

        /**
         * select id, username, realname from user where username = 'a' and password = 'c4ca4238a0b923820dcc509a6f75849b';
         * 先将sql放在数据库运行一下，如果没问题，在拷贝代码中
         */
        String sql = "select id, username, realname,password from m_user where username = ? and password = ?";

        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setObject(1, username);
            ps.setObject(2, password);

            ResultSet rs = ps.executeQuery();  //执行查询

            //表示有数据, 因为根据条件判断可能没有数据
            if(rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
            }
            // 一定一定要关
            DbUtils.colse(rs, ps, connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }
}
